#include "CodefolderLogs.hpp"

CodefolderLogs::CodefolderLogs(string xmlFile)
{
  m_success = false;
  m_file = xmlFile;

  m_document = xmlParseFile(m_file.c_str());
  if (m_document != NULL)
  {
    m_root = xmlDocGetRootElement(m_document);
    if (m_root != NULL)
      if (xmlStrcmp(m_root->name, reinterpret_cast<const xmlChar*>("snippets")) == 0)
        m_success = true;
  }
}

CodefolderLogs::~CodefolderLogs()
{
  if (m_document != NULL)
	  xmlFreeDoc(m_document);
}

bool CodefolderLogs::LoadSuccess()
{
  return m_success;
}

void CodefolderLogs::Fetch(SnippetList& list)
{
  for (m_snippet = m_root->children; m_snippet != NULL; m_snippet = m_snippet->next)
  {
    if (m_snippet->type != XML_ELEMENT_NODE)
      continue;

    Snippet* snippet = new Snippet();
    for (m_snippetInfo = m_snippet->children; m_snippetInfo != NULL; m_snippetInfo = m_snippetInfo->next)
    {
      if (m_snippet->type != XML_ELEMENT_NODE)
        continue;

      string content(reinterpret_cast<const char*>(xmlNodeGetContent(m_snippetInfo)));

      // grab snippet ID
      if (xmlStrcmp(m_snippetInfo->name, reinterpret_cast<const xmlChar*>("id")) == 0)
        snippet->m_snippetId = content;

      // grab snippet description
      if (xmlStrcmp(m_snippetInfo->name, reinterpret_cast<const xmlChar*>("desc")) == 0)
        snippet->m_description = content;

      // grab snippet language
      if (xmlStrcmp(m_snippetInfo->name, reinterpret_cast<const xmlChar*>("lang")) == 0)
        snippet->m_language = content;
    }
    list.push_back(snippet);
  }
}

void CodefolderLogs::Save(SnippetList& list)
{
  m_snippet = xmlNewNode(NULL, reinterpret_cast<const xmlChar*>("snippets"));

  for (SnippetList::iterator i = list.begin(); i != list.end(); i++)
  {
    // create a new <snippet> node
    xmlNodePtr snippet = xmlNewTextChild(m_snippet, NULL,
      reinterpret_cast<const xmlChar*>("snippet"), NULL);

    // #1 - save snippet ID
    xmlNewTextChild(snippet, NULL,
      reinterpret_cast<const xmlChar*>("id"),
      reinterpret_cast<const xmlChar*>((*i)->m_snippetId.c_str())
    );

    // #2 - save snippet description
    xmlNewTextChild(snippet, NULL,
      reinterpret_cast<const xmlChar*>("desc"),
      reinterpret_cast<const xmlChar*>((*i)->m_description.c_str())
    );

    // #3 - save snippet language
    xmlNewTextChild(snippet, NULL,
      reinterpret_cast<const xmlChar*>("lang"),
      reinterpret_cast<const xmlChar*>((*i)->m_language.c_str())
    );
  }

  // create a new document if one wasn't already there
  if (m_document == NULL)
    m_document = xmlNewDoc(reinterpret_cast<const xmlChar*>("1.0"));

  xmlDocSetRootElement(m_document, m_snippet);
  xmlSaveFormatFile(m_file.c_str(), m_document, 1);
}